export default {
 
    /** 
     * 主执行函数，记得在子类中重写该方法
     * @param {object} paramObj 任务参数对象
     * @param {int} index 当前执行索引
    */
  async Main(paramObj,index) {
    console.log(`index:${index} param:${paramObj}`);
  },

  /**
   * 执行任务Function
   * @param {*} AccountObj 账号对象
   * @param {*} index 当前执行索引
   */
  taskfuc(AccountObj, index) {
    return new Promise(async (resolve, reject) => {
      try {
        await this.Main(AccountObj, index);
        resolve("success");
      } catch (err) {
        reject(err);
      }
    });
  },

  /**
   *
   * @param {*} tasks 任务方法
   * @param {*} maxConcurrency
   * @returns
   */
  limitConcurrency(tasks, maxConcurrency) {
    let runningCount = 0;
    let index = 0;
    return new Promise((resolve, reject) => {
      function runTask() {
        if (runningCount >= maxConcurrency || index >= tasks.length) {
          if (index >= tasks.length && runningCount === 0) {
            resolve();
          }
          return;
        }
        runningCount++;
        const task = tasks[index++];
        task()
          .then(() => {
            runningCount--;
            runTask();
          })
          .catch((error) => {
            reject(error);
          });

        runTask();
      }
      runTask();
    });
  },
  
  /**
   * 
   * 启动任务
   * @param {object} accounts  账号对象
   * @param {int} repeatTime  重复次数
   * @param {int} maxConcurrency  最大并发数
   * @returns 
   */
  startTask(accounts, repeatTime, maxConcurrency) {
    const tasks = accounts.map((accounts, index) => () => {
      return this.taskfuc(accounts, index);
    });
    const repeatedTasks = Array.from(
      { length: repeatTime },
      () => tasks
    ).flat();
    return  this.limitConcurrency(repeatedTasks, maxConcurrency);
  },


};
